import { Module } from 'vuex'
import { rootState } from '../types'
import { loginState } from './types'
import { Account } from '../../service/login/types'
import { mapMenuToRoute } from '@/util/map-menu'

import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusById
} from '../../service/login/login'
import localCache from '../../util/cache'
import router from '@/router'

const loginModule: Module<loginState, rootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenu: []
    }
  },
  mutations: {
    // 保存token
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenu(state, userMenu: any) {
      state.userMenu = userMenu
      // 映射userMenu->route
      // const userMenu = (store.state as any).loginModule.userMenu
      const routes = mapMenuToRoute(userMenu)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
    }
  },
  actions: {
    async accountLoginAction({ commit }, payload: Account) {
      // 请求登录信息
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit('changeToken', token)
      localCache.setCache('token', token)

      // 请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)

      // 请求登陆菜单
      const userMenuResult = await requestUserMenusById(userInfo.role.id)
      const userMenu = userMenuResult.data
      commit('changeUserMenu', userMenu)
      localCache.setCache('userMenu', userMenu)

      // 跳转到首页
      router.push('./main')
    },
    loadloginLocal({ commit }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('changeToken', token)
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenu = localCache.getCache('userMenu')
      if (userMenu) {
        commit('changeUserMenu', userMenu)
      }
    }
  }
}

export default loginModule
